package es.uoc.mxpdroid.algorithm;

import es.uoc.mxpdroid.entity.RasterLayer;



public class ReclassifyAlgorithm{

   public static final String INPUT                      = "INPUT";
   public static final String METHOD                     = "METHOD";
   public static final String RECLASS                    = "RECLASS";

   public static final int    METHOD_LOWER_THAN          = 0;
   public static final int    METHOD_LOWER_THAN_OR_EQUAL = 1;

   private RasterLayer grid;
   private RasterLayer result;
   private float[][] reclassTable;
   private int m_iMethod;

   public ReclassifyAlgorithm(RasterLayer in, float[][] reclassLaw, int method) {

      grid = in;
      reclassTable = reclassLaw;
      m_iMethod = method;
      result = new RasterLayer(in.getLayerType());
      result.initFromLayer(grid);
      
      processAlgorithm();
   }

   public RasterLayer getResultLayer(){
       return result;
   }
   
   private void processAlgorithm() {

      int i;
      int x, y;
      int iNX, iNY;
      double dCellValue;
      double dMinValue, dMaxValue;



      iNX = grid.getNX();
      iNY = grid.getNY();
      

      if (m_iMethod == ReclassifyAlgorithm.METHOD_LOWER_THAN) {
         for (y = 0; (y < iNY) ; y++) {
            for (x = 0; x < iNX; x++) {
               dCellValue = grid.getCellValueAsDouble(x, y);
               for (i = 0; i < reclassTable.length; i++) {
                  dMinValue = reclassTable[i][0];
                  if (dCellValue >= dMinValue) {
                     dMaxValue = reclassTable[i][1];
                     if (dCellValue < dMaxValue) {
                        result.setCellValue(x, y, reclassTable[i][2]);
                        break;
                     }
                  }
               }
               //if no entry in the table
//               if (i >= reclassTable.length) {
//            	  result.setNoDataAtCell(x, y);
//               }
            }
         }
      }
      else {
    	  for (y = 0; (y < iNY) ; y++) {
              for (x = 0; x < iNX; x++) {
                 dCellValue = grid.getCellValueAsDouble(x, y);
                 for (i = 0; i < reclassTable.length; i++) {
                    dMinValue = reclassTable[i][0];
                    if (dCellValue >= dMinValue) {
                       dMaxValue = reclassTable[i][1];
                       if (dCellValue <= dMaxValue) {
                          result.setCellValue(x, y, reclassTable[i][2]);
                          break;
                       }
                    }
                 }
//                 if (i >= reclassTable.length - 1) {
//                	 result.setNoDataAtCell(x, y);
//                 }
              }
           }
      }

   }

}
